package cool.mtc.swagger.filter;

import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.servers.Server;
import springfox.documentation.oas.web.OpenApiTransformationContext;
import springfox.documentation.oas.web.WebMvcOpenApiTransformationFilter;
import springfox.documentation.service.Documentation;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.DocumentationCache;
import springfox.documentation.spring.web.plugins.Docket;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author 明河
 */
public abstract class AbstractCustomServerFilter implements WebMvcOpenApiTransformationFilter {

    @Override
    public OpenAPI transform(OpenApiTransformationContext<HttpServletRequest> context) {
        OpenAPI openApi = context.getSpecification();
        // 从参数中获取group
        String groupParam = context.request().isPresent() ? context.request().get().getParameter("group") : null;
        String groupName = Optional.ofNullable(groupParam).orElse(Docket.DEFAULT_GROUP_NAME);
        // 从缓存中获取servers
        Documentation documentation = this.getDocumentationCache().documentationByGroup(groupName);
        if (null != documentation && null != documentation.getServers() && !documentation.getServers().isEmpty()) {
            openApi.servers(this.transServers(documentation.getServers()));
        }
        return openApi;
    }

    @Override
    public boolean supports(DocumentationType delimiter) {
        return delimiter == DocumentationType.OAS_30;
    }

    abstract DocumentationCache getDocumentationCache();

    /**
     * server类型转换
     */
    private List<Server> transServers(List<springfox.documentation.service.Server> servers) {
        List<io.swagger.v3.oas.models.servers.Server> resultServerList = new ArrayList<>();
        for (springfox.documentation.service.Server server : servers) {
            io.swagger.v3.oas.models.servers.Server resultServer = new io.swagger.v3.oas.models.servers.Server();
            resultServer.setUrl(server.getUrl());
            resultServer.setDescription(server.getDescription());
            resultServerList.add(resultServer);
        }
        return resultServerList;
    }
}
